package cn.ryh.fileupload.config;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.io.IOException;

/**
 * @author Rao
 * @Description
 * @create 2022-04-16 14:53
 */
@Configuration
public class FileUploadConfig {
    /**
     * 设置文件大小限制
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超了，页面会抛出异常信息，这时候就需要进行异常信息的处理了;
        factory.setMaxFileSize(DataSize.ofMegabytes(1024));
        // 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(2048));
        //设置存储文件的目录位置  new File("").getCanonicalPath()项目根路径
        try {
            Resource resource = new ClassPathResource("");
            System.out.println(resource.getFile().getAbsolutePath());
            factory.setLocation(resource.getFile().getCanonicalPath()+"\\");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return factory.createMultipartConfig();
    }
}
